/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.uff.es2.xadrez.ia;

import br.uff.es2.xadrez.core.Board;
import br.uff.es2.xadrez.core.Piece;
import java.util.ArrayList;
import java.util.Collection;

/**
 *
 * @author Luiz Nunes
 */
public class InteligenciaArtificial {

    public int[][] move(Board board)
    {
        int[] oldPosition;

        Collection<int[]> validPiecesPositions = new ArrayList<int[]>();
        Collection<int[]> validMovesPositions = new ArrayList<int[]>();

        for (int i = 0; i < board.getBoard().length; i++) {
            Piece[] pieces = board.getBoard()[i];
            for (int j = 0; j < pieces.length; j++) {
               Piece piece = pieces[j];
               if(piece != null && piece.getColor().equals(board.getTurn()))
               {
                   int[] validPosition = {i,j};
                   validPiecesPositions.add(validPosition);
               }
            }
        }
        if(validPiecesPositions.size() == 0)
            return null;

        do
        {
            double random = Math.random();
            int index = (int) Math.floor(random*validPiecesPositions.size());
            oldPosition = (int[]) validPiecesPositions.toArray()[index];
            Piece piece = board.getBoard()[oldPosition[0]][oldPosition[1]];
            int[][] avaiableMoves = piece.getAvaiableMoves(oldPosition, board.getBoard());
            for (int i = 0; i < avaiableMoves.length; i++) {
                for (int j = 0; j < avaiableMoves.length; j++) {
                    if(avaiableMoves[i][j] == 1)
                    {
                        int[] validMove = {i,j};
                        validMovesPositions.add(validMove);
                    }
                }
            }
            if(validMovesPositions.size() == 0)
                validPiecesPositions.remove(oldPosition);
            else
                break;

            if(validPiecesPositions.size() == 0)
                return null;

        }while(true);

        double random = Math.random();
        int index = (int) Math.floor(random*validMovesPositions.size());
        int[] newPosition = (int[]) validMovesPositions.toArray()[index];

        int[][] pieceMove = {oldPosition, newPosition};
        return(pieceMove);
    }
    
}
